#include "attributestab.h"
#include "comboboxdelegate.h"

AttributesTab::AttributesTab(AED_Archtype *arch, QWidget *parent) :
    QWidget(parent)
{
    m_model = 0;
    m_view = new QTableView();


    ComboBoxDelegate *delegate = new ComboBoxDelegate();
    delegate->AddItem("int");
    delegate->AddItem("float");
    delegate->AddItem("string");
    delegate->AddItem("bool");
    m_view->setItemDelegateForColumn(0,delegate);
    m_view->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_view->setSelectionMode(QAbstractItemView::SingleSelection);
     m_view->horizontalHeader()->setResizeMode(QHeaderView::Stretch);


    QVBoxLayout *main_layout = new QVBoxLayout();

    this->setLayout(main_layout);

    QHBoxLayout *bbox = new QHBoxLayout;
    QPushButton *addattr = new QPushButton("Add Attribute");
    QPushButton *removeattr = new QPushButton("Remove Attribute");
    bbox->addWidget(addattr);
    bbox->addWidget(removeattr);

    main_layout->addLayout(bbox);
    bbox->setAlignment(Qt::AlignLeft);
    main_layout->addWidget(m_view);

    connect(addattr, SIGNAL(pressed()),
             this, SLOT(AddAttribute()));
    connect(removeattr, SIGNAL(pressed()),
             this, SLOT(RemoveAttribute()));

    setArchtype(arch);
}

void AttributesTab::AddAttribute(){
    m_model->AddAttribute("int","NEW_ATTR");
}

void AttributesTab::RemoveAttribute(){
    QModelIndexList lstIndex ;

    QItemSelection ranges = m_view->selectionModel()->selection();
    for (int i = 0; i < ranges.count(); ++i){
        QModelIndex parent = ranges.at(i).parent();
        int right = ranges.at(i).model()->columnCount(parent) - 1;
        if (ranges.at(i).left() == 0 && ranges.at(i).right() == right)
            for (int r = ranges.at(i).top(); r <= ranges.at(i).bottom(); ++r)
                lstIndex.append(ranges.at(i).model()->index(r, 0, parent));
    }
    for(int i=0; i<lstIndex.size();i++){
        QModelIndex index = lstIndex.at(i);
        if(index.isValid()){
             m_model->RemoveAttribute(index.row());
        }
    }
}

void AttributesTab::setArchtype(AED_Archtype* arch){
    if(arch){
        this->setEnabled(true);
        delete m_model;
        m_model = new AttributeModel(arch);
        m_view->setModel(m_model);
    }else{
        this->setEnabled(false);
    }
}
